package com.easemob.helpdesk.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.helpdesk.activity.ChatActivity;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.activity.UserActivity;
import com.easemob.helpdesk.activity.history.SearchHistorySessionActivity;
import com.easemob.helpdesk.bean.MsgChat;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.bean.UserInfo;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DialogUtils;
import com.easemob.helpdesk.widget.chatrow.BaseMsgViewHolder;
import com.easemob.helpdesk.widget.chatrow.BaseViewHolder;
import com.easemob.helpdesk.widget.chatrow.FileViewHolder;
import com.easemob.helpdesk.widget.chatrow.ImageViewHolder;
import com.easemob.helpdesk.widget.chatrow.MsgImageViewHolder;
import com.easemob.helpdesk.widget.chatrow.MsgTxtViewHolder;
import com.easemob.helpdesk.widget.chatrow.MsgVideoViewHolder;
import com.easemob.helpdesk.widget.chatrow.MsgVoiceViewHolder;
import com.easemob.helpdesk.widget.chatrow.TxtViewHolder;
import com.easemob.helpdesk.widget.chatrow.VideoViewHolder;
import com.easemob.helpdesk.widget.chatrow.VoiceViewHolder;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.entity.HDMessage;
import com.hyphenate.kefusdk.manager.session.SessionManager;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import retrofit2.Call;


/**
 * Created by wsj on 2018/5/22.
 */

public class UserChatAdapter extends RecyclerView.Adapter<BaseMsgViewHolder>{

    private static final int MESSAGE_TYPE_SENT_TXT = 0;
    private static final int MESSAGE_TYPE_RECV_TXT = 1;
    private static final int MESSAGE_TYPE_SENT_IMAGE = 2;
    private static final int MESSAGE_TYPE_RECV_IMAGE = 3;
    private static final int MESSAGE_TYPE_RECV_ORDER = 4;
    private static final int MESSAGE_TYPE_SENT_VOICE = 6;
    private static final int MESSAGE_TYPE_RECV_VOICE = 7;
    private static final int MESSAGE_TYPE_SENT_FILE = 8;
    private static final int MESSAGE_TYPE_RECV_FILE = 9;
    private static final int MESSAGE_TYPE_SENT_ROBOTMENU = 10;
    private static final int MESSAGE_TYPE_RECV_ROBOTMENU = 11;
    private static final int MESSAGE_TYPE_RECALL_MESSAGE = 12;
    private static final int MESSAGE_TYPE_SENT_VIDEO = 13;
    private static final int MESSAGE_TYPE_RECV_VIDEO = 14;


    private LayoutInflater inflater;
    private Activity mActivity;
    private Context mContext;
    public int mMinItemWidth;
    public int mMaxItemWidth;

    public View animView;
    public int animStatus = -1; // -1 not play; 0 sent play; 1 received play
    public boolean isAppChannel;
    private List<MsgChat> messageList;
    private RecyclerView mRecyclerView;

    private String userPhone;// 用户手机号
    private String username;

    /**
     * 加载提示Dialog
     */
    public Dialog pd = null;

    public UserChatAdapter(){

    }

    public UserChatAdapter(Activity activity, List<MsgChat> messageList, RecyclerView recyclerView) {
        this.mContext = activity.getBaseContext();
        this.mActivity = activity;
        this.mRecyclerView = recyclerView;
        animStatus = -1;
        this.messageList = messageList;
        inflater = LayoutInflater.from(mContext);
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();

        wm.getDefaultDisplay().getMetrics(displayMetrics);
        mMaxItemWidth = (int) (displayMetrics.widthPixels * 0.4f);
        mMinItemWidth = (int) (displayMetrics.widthPixels * 0.15f);

    }

    @Override
    public BaseMsgViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View convertView = null;
        BaseMsgViewHolder holder = null;

        switch (viewType) {
            case MESSAGE_TYPE_RECV_TXT:
                convertView = inflater.inflate(R.layout.row_received_message, parent, false);
                holder = new MsgTxtViewHolder(mActivity, this, convertView);
                break;
            case MESSAGE_TYPE_SENT_TXT:
                convertView = inflater.inflate(R.layout.row_sent_message, parent, false);
                holder = new MsgTxtViewHolder(mActivity, this, convertView);
                break;
            case MESSAGE_TYPE_RECV_IMAGE:
                convertView = inflater.inflate(R.layout.row_received_picture, parent, false);
                holder = new MsgImageViewHolder(mActivity, this, convertView);
                break;
            case MESSAGE_TYPE_SENT_IMAGE:
                convertView = inflater.inflate(R.layout.row_sent_picture, parent, false);
                holder = new MsgImageViewHolder(mActivity, this, convertView);
                break;
            case MESSAGE_TYPE_RECV_VOICE:
                convertView = inflater.inflate(R.layout.row_received_voice, parent, false);
                holder = new MsgVoiceViewHolder(mActivity, this, convertView);
                break;
            case MESSAGE_TYPE_SENT_VOICE:
                convertView = inflater.inflate(R.layout.row_sent_voice, parent, false);
                holder = new MsgVoiceViewHolder(mActivity, this, convertView);
                break;
            case MESSAGE_TYPE_RECV_VIDEO:
                convertView = inflater.inflate(R.layout.row_received_video, parent, false);
                holder = new MsgVideoViewHolder(mActivity, this, convertView);
                break;
            case MESSAGE_TYPE_SENT_VIDEO:
                convertView = inflater.inflate(R.layout.row_sent_video, parent, false);
                holder = new MsgVideoViewHolder(mActivity, this, convertView);
                break;
            default:
                break;
//            default:break;
//            default:break;
        }
        //-------------------性能优化注释代码begin-----------------
//        convertView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        //-------------------性能优化注释代码end-----------------
        return holder;
    }

    @Override
    public void onBindViewHolder(BaseMsgViewHolder holder, int position) {
        if (position > messageList.size()) {
            return;
        }
        final MsgChat message = messageList.get(position);


        Glide.with(mActivity).load(message.getAvatar())
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.drawable.default_customer_avatar).error(R.drawable.default_customer_avatar)
                .into(holder.ivAvatar);

        if(message.getDirect().equals("WX")){//接收方
            holder.ivAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(message.getId() != 0){
                        getUserInfo(message.getUid());
                    }
                }
            });
        }

        holder.handleMessage(message, position);

    }

    public void showLoading() {
        //显示登录提示对话框
        pd = DialogUtils.getLoadingDialog(this.mActivity, "加载中...");
        pd.show();
    }

    public void hideLoading() {
        if(pd != null && pd.isShowing()){
            pd.dismiss();
        }
    }


    private void getUserInfo(long id) {
        ApiService apiService = HKHttpUtils.getApiService();
        Call<BaseResponse<User>> call = apiService.getUserById(MainActivity.ticket,String.valueOf(id));
        call.enqueue(new HKResponseResultCallBack<User>() {
            @Override
            public void onSuccess(User user) {
                hideLoading();
                Intent intent = new Intent();
                intent.setClass(mActivity, UserActivity.class);
                intent.putExtra("id", user.getId());
                intent.putExtra("phone", user.getPhone());
                intent.putExtra("wxHeader", user.getWxHeader());
                intent.putExtra("homeAddress",  user.getHomeAddress());
                intent.putExtra("idcardNumber", user.getIdcardNumber());

                String wxname = user.getWxName();
                try {
                    if(!CommonUtils.isBlank(wxname)) {
                        String decodeStr = URLDecoder.decode(wxname, "utf-8");
                        intent.putExtra("wxname", decodeStr);
                    }else{
                        intent.putExtra("wxname", "");
                    }

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    intent.putExtra("wxname", wxname);
                }

                String name = user.getName();

                if(!CommonUtils.isBlank(name)){
                    intent.putExtra("name", name);
                }else{
                    intent.putExtra("name", "");
                }

                intent.putExtra("originType", "rest");
                intent.putExtra("techChannelName", "");
//					intent.putExtra("visitorid", visitorId);
                intent.putExtra("chatGroupId", 0L);
                mActivity.startActivity(intent);
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                hideLoading();
                Toast.makeText(mContext, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(Call call, Throwable t) {
                hideLoading();
                Toast.makeText(mContext, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });

//        OkHttpClient okHttpClient = new OkHttpClient();
//
//        showLoading();
//
//        RequestBody body = new FormBody.Builder()
//                .add("uid", String.valueOf(id))
//                .build();
//
//        Request request = new Request.Builder()
//                .url(BuildConfig.API_URL + "account/findUserById")
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//                hideLoading();
//                Toast.makeText(mActivity, "请求失败", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//                final String res = response.body().string();
//                final UserInfo result = CommonUtils.parseJsonWithGson(res, UserInfo.class);
//                mActivity.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        hideLoading();
//                        if(result.getData() != null){
//                            Intent intent = new Intent();
//                            intent.setClass(mActivity, UserActivity.class);
//                            intent.putExtra("id", result.getData().getId());
//                            intent.putExtra("phone", result.getData().getPhone());
//                            intent.putExtra("wxHeader", result.getData().getWxHeader());
//                            intent.putExtra("homeAddress",  result.getData().getHomeAddress());
//                            intent.putExtra("idcardNumber", result.getData().getIdcardNumber());
//
//                            String wxname = result.getData().getWxName();
//                            try {
//                                if(!CommonUtils.isBlank(wxname)) {
//                                    String decodeStr = URLDecoder.decode(wxname, "utf-8");
//                                    intent.putExtra("wxname", decodeStr);
//                                }else{
//                                    intent.putExtra("wxname", "");
//                                }
//
//                            } catch (UnsupportedEncodingException e) {
//                                e.printStackTrace();
//                                intent.putExtra("wxname", wxname);
//                            }
//
//                            String name = result.getData().getName();
//
//                            if(!CommonUtils.isBlank(name)){
//                                intent.putExtra("name", name);
//                            }else{
//                                intent.putExtra("name", "");
//                            }
//
//                            intent.putExtra("originType", "rest");
//                            intent.putExtra("techChannelName", "");
////					intent.putExtra("visitorid", visitorId);
//                            intent.putExtra("chatGroupId", 0L);
//                            mActivity.startActivity(intent);
//
//                        }
//                    }
//                });
//
//            }
//        });

    }

    public MsgChat getItem(int position) {
        if (position < this.messageList.size()) {
            return this.messageList.get(position);
        }

        return null;
    }

    /**
     * 刷新页面
     */
    public void refresh() {
        notifyDataSetChanged();
    }

    /**
     * 刷新页面，选择最后一个
     */
    public void refreshSelectLast() {
        if (messageList.size() > 0) {
            mRecyclerView.scrollToPosition(messageList.size() - 1);
        }
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }


    @Override
    public int getItemViewType(int position) {
        MsgChat message = messageList.get(position);
        if (message == null) {
            return -1;
        }

        if(message.getType().equals("txt")){
            return message.getDirect().equals("WX")?MESSAGE_TYPE_RECV_TXT:MESSAGE_TYPE_SENT_TXT;
        }else if(message.getType().equals("img")){
            return message.getDirect().equals("WX")?MESSAGE_TYPE_RECV_IMAGE:MESSAGE_TYPE_SENT_IMAGE;
        }else if(message.getType().equals("audio")){
            return message.getDirect().equals("WX")?MESSAGE_TYPE_RECV_VOICE:MESSAGE_TYPE_SENT_VOICE;
        }else if(message.getType().equals("video")){
            return message.getDirect().equals("WX")?MESSAGE_TYPE_RECV_VIDEO:MESSAGE_TYPE_SENT_VIDEO;
        }

        return super.getItemViewType(position);
    }
}
